package com.xqboss.web.controller.user;

import cn.hutool.core.bean.BeanUtil;
import com.xqboss.apps.convert.user.WithdrawRecordConverter;
import com.xqboss.apps.domain.user.SysUserWallet;
import com.xqboss.apps.domain.user.UserAssetWrench;
import com.xqboss.apps.domain.user.UserAssetWrenchRecord;
import com.xqboss.apps.dto.user.*;
import com.xqboss.apps.enums.user.UserWalletEnum;
import com.xqboss.apps.enums.user.WalletChangeDirectionEnum;
import com.xqboss.apps.enums.user.WalletChangeTypeEnum;
import com.xqboss.apps.enums.user.WalletWrenchChangeTypeEnum;
import com.xqboss.apps.service.sys.ConfigService;
import com.xqboss.apps.service.user.SysUserWalletRecordService;
import com.xqboss.apps.service.user.SysUserWalletService;
import com.xqboss.apps.service.user.UserAssetWrenchRecordService;
import com.xqboss.apps.service.user.UserAssetWrenchService;
import com.xqboss.apps.vo.sys.WalletProfileVo;
import com.xqboss.apps.vo.user.*;
import com.xqboss.apps.vo.user.SysUserWalletRecordVo;
import com.xqboss.apps.vo.user.WithdrawRecordVo;
import com.xqboss.common.annotation.Log;
import com.xqboss.common.annotation.RepeatSubmit;
import com.xqboss.common.core.controller.BaseController;
import com.xqboss.common.core.domain.R;
import com.xqboss.common.enums.BusinessType;
import com.xqboss.common.exception.ServiceException;
import com.xqboss.common.utils.LocalDateUtils;
import com.xqboss.common.utils.poi.ExcelUtil;
import com.xqboss.system.service.ISysConfigService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 用户钱包相关控制器
 * </p>
 *
 * @author Trent
 * @date 2023/8/17
 */

@Api(tags = "钱包-用户钱包管理")
@RestController("WebUserWalletController")
@RequestMapping("/web/user/wallet")
public class UserWalletController extends BaseController {

    @Autowired
    private SysUserWalletService userWalletService;

    @Autowired
    private SysUserWalletRecordService sysUserWalletRecordService;

    @Autowired
    private WithdrawRecordConverter withdrawRecordConverter;

    @Autowired
    private ConfigService configService;
    @Autowired
    private ISysConfigService sysConfigService;

    /**
     * 获取钱包配置接口
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('web:user:wallet:config:info')")
    @ApiOperation("获取钱包配置")
    @GetMapping("config/info")
    public R<WalletProfileVo> configInfo() {
        WalletProfileVo walletConfig = configService.getWalletConfig();
        return R.ok(walletConfig);
    }

    /**
     * 更新钱包配置接口
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('web:user:wallet:config:update')")
    @ApiOperation("更新钱包配置")
    @Log(title = "钱包配置", businessType = BusinessType.UPDATE)
    @PutMapping("config/update")
    public R<WalletProfileVo> configInfo(@Validated @RequestBody WalletProfileDto dto) {
        configService.updateWalletConfig(dto);
        WalletProfileVo vo = configService.getWalletConfig();
        return R.ok(vo);
    }


    /**
     * 用户钱包详情
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('web:user:wallet:detail')")
    @ApiOperation("用户钱包详情")
    @GetMapping("detail")
    public R<SysUserWallet> detail(@Validated UserWalletDetailDto params) {
        // 用户钱包详情
        SysUserWallet wallet = userWalletService.getWallet(params.getUserId(), params.getType());
        return R.ok(wallet);
    }

    /**
     * 用户钱包操作
     *
     * @return
     */
    @RepeatSubmit(interval = 1000, justUrl = true)
    @PreAuthorize("@ss.hasPermi('web:user:wallet:change')")
    @ApiOperation("用户钱包修改")
    @Log(title = "钱包操作", businessType = BusinessType.UPDATE)
    @PutMapping("change")
    public R change(@Validated @RequestBody ChangeUserWalletDto params) {
        return userWalletService.handleWalletChange(params);
    }

    @PreAuthorize("@ss.hasPermi('web:user:wallet:record-list')")
    @ApiOperation("钱包变动记录")
    @GetMapping("record-list")
    public R getRecordList(@Validated WithdrawRecordListDto params) {
        params.startPageAndOrder();
        if (params.getWalletType() == UserWalletEnum.WRENCH){
            params.setUserId(params.getUserId());
            // 扳手额外处理
            List<SysUserWalletRecordVo> list = sysUserWalletRecordService.getwrenchRecordList(params);
            List<WithdrawRecordVo> voList = withdrawRecordConverter.toVoList(list);
            return R.ok(voList,list);
        }
        // 热豆或者现金
        List<SysUserWalletRecordVo> list = sysUserWalletRecordService.getRecordList(params);
        List<WithdrawRecordVo> voList = withdrawRecordConverter.toVoList(list);
        return R.ok(voList, list);
    }

    /**
     * 用户余额导出
     */
    @RepeatSubmit(interval = 1000, justUrl = true)
    @PreAuthorize("@ss.hasPermi('web:user:wallet:export')")
    @ApiOperation("钱包变动记录导出")
    @Log(title = "钱包变动记录导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(@Validated WithdrawRecordListDto params, HttpServletResponse response) {
        if (!Objects.isNull(params.getCreateTimeStart()) &&
            !Objects.isNull(params.getCreateTimeEnd()) &&
            LocalDateUtils.getDifferentDays(params.getCreateTimeStart().toLocalDate(), params.getCreateTimeEnd().toLocalDate()) > 7) {
            throw new ServiceException("开始结束时间不能超过7天");
        }
        params.startOrder();
        params.setPageSize(null);
        List<SysUserWalletRecordVo> list = sysUserWalletRecordService.getRecordList(params);
        List<WithdrawRecordVo> voList = withdrawRecordConverter.toVoList(list);
        List<UserWalletListExportVo> exportList = BeanUtil.copyToList(voList,UserWalletListExportVo.class);
        ExcelUtil<UserWalletListExportVo> util = new ExcelUtil<>(UserWalletListExportVo.class);
        util.exportExcel(response, exportList, "账户余额","钱包变动记录("+ LocalDate.now()+")");
    }


//    @PreAuthorize("@ss.hasPermi('web:user:wallet:adjust')")
//    @ApiOperation("调整余额")
//    @Log(title = "修改用户钱包余额", businessType = BusinessType.UPDATE)
//    @PostMapping("adjust_balance")
//    public R adjustBalance(@Validated @RequestBody WebWalletAdjustDto dto) {
//        userWalletService.adjustBalance(dto);
//        return R.ok();
//    }


    @PreAuthorize("@ss.hasPermi('web:user:wallet:updateHotBeansAndWrench')")
    @ApiOperation("修改热豆和扳手和力豆配置")
    @PostMapping("updateHotBeansAndWrenchConfig")
    public R updateHotBeansConfig(@RequestBody @NotEmpty @Validated Map<String, String> map) {
        configService.updateHotBeansConfig(map);
        return R.ok();
    }


    @PreAuthorize("@ss.hasPermi('web:user:wallet:selectHotBeansConfig')")
    @ApiOperation("获取热豆配置")
    @GetMapping("selectHotBeansConfig")
    public R selectHotBeansConfig() {
        String str = "热豆";
        Map<String, String> configs = sysConfigService.selectHotBeansConfig(str);
        return R.ok(configs);
    }


    @PreAuthorize("@ss.hasPermi('web:user:wallet:selectWrenchConfig')")
    @ApiOperation("获取扳手配置")
    @GetMapping("selectWrenchConfig")
    public R selectWrenchConfig() {
        String str = "扳手";
        Map<String, String> configs = sysConfigService.selectWrenchConfig(str);
        return R.ok(configs);
    }

    @PreAuthorize("@ss.hasPermi('web:user:wallet:selectLidouConfig')")
    @ApiOperation("获取力豆配置")
    @GetMapping("selectLidouConfig")
    public R selectLidouConfig() {
        String str = "力豆";
        Map<String, String> configs = sysConfigService.selectLidouConfig(str);
        return R.ok(configs);
    }

}
